#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
解释器模式 (Interpreter Pattern) - Python实现详解

解释器模式是一种行为设计模式，它定义了一种语言的文法表示，
并定义一个解释器来处理这种语言中的句子。

与Java对比：
1. Python的动态特性使得解释器更加灵活
2. Python支持元编程，可以动态创建解释器
3. Python的正则表达式和字符串处理能力更强
4. Python的eval()和exec()提供了内置的解释能力

作者: Assistant
日期: 2024
"""

import re
import ast
import operator
import time
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Union, Callable
from dataclasses import dataclass
from enum import Enum
import json
from collections import defaultdict


# ============================================================================
# 1. 传统解释器模式实现
# ============================================================================

class Expression(ABC):
    """
    抽象表达式类
    定义解释器的接口
    """
    
    @abstractmethod
    def interpret(self, context: Dict[str, Any]) -> Any:
        """解释表达式"""
        pass
    
    @abstractmethod
    def __str__(self) -> str:
        """返回表达式的字符串表示"""
        pass


class TerminalExpression(Expression):
    """
    终结符表达式
    实现与文法中的终结符相关联的解释操作
    """
    
    def __init__(self, data: str):
        self.data = data
    
    def interpret(self, context: Dict[str, Any]) -> Any:
        """解释终结符"""
        # 如果是变量，从上下文中获取值
        if self.data in context:
            return context[self.data]
        
        # 尝试解析为数字
        try:
            if '.' in self.data:
                return float(self.data)
            else:
                return int(self.data)
        except ValueError:
            pass
        
        # 尝试解析为布尔值
        if self.data.lower() == 'true':
            return True
        elif self.data.lower() == 'false':
            return False
        
        # 尝试解析为字符串（去掉引号）
        if (self.data.startswith('"') and self.data.endswith('"')) or \
           (self.data.startswith("'") and self.data.endswith("'")):
            return self.data[1:-1]
        
        # 返回原始字符串
        return self.data
    
    def __str__(self) -> str:
        return self.data


class BinaryExpression(Expression):
    """
    二元表达式基类
    """
    
    def __init__(self, left: Expression, right: Expression):
        self.left = left
        self.right = right
    
    def interpret(self, context: Dict[str, Any]) -> Any:
        """解释二元表达式"""
        left_val = self.left.interpret(context)
        right_val = self.right.interpret(context)
        return self._operate(left_val, right_val)
    
    @abstractmethod
    def _operate(self, left: Any, right: Any) -> Any:
        """执行具体的操作"""
        pass


class AddExpression(BinaryExpression):
    """
    加法表达式
    """
    
    def _operate(self, left: Any, right: Any) -> Any:
        return left + right
    
    def __str__(self) -> str:
        return f"({self.left} + {self.right})"


class SubtractExpression(BinaryExpression):
    """
    减法表达式
    """
    
    def _operate(self, left: Any, right: Any) -> Any:
        return left - right
    
    def __str__(self) -> str:
        return f"({self.left} - {self.right})"


class MultiplyExpression(BinaryExpression):
    """
    乘法表达式
    """
    
    def _operate(self, left: Any, right: Any) -> Any:
        return left * right
    
    def __str__(self) -> str:
        return f"({self.left} * {self.right})"


class DivideExpression(BinaryExpression):
    """
    除法表达式
    """
    
    def _operate(self, left: Any, right: Any) -> Any:
        if right == 0:
            raise ValueError("除数不能为零")
        return left / right
    
    def __str__(self) -> str:
        return f"({self.left} / {self.right})"


class CompareExpression(BinaryExpression):
    """
    比较表达式基类
    """
    pass


class EqualsExpression(CompareExpression):
    """
    等于表达式
    """
    
    def _operate(self, left: Any, right: Any) -> Any:
        return left == right
    
    def __str__(self) -> str:
        return f"({self.left} == {self.right})"


class GreaterThanExpression(CompareExpression):
    """
    大于表达式
    """
    
    def _operate(self, left: Any, right: Any) -> Any:
        return left > right
    
    def __str__(self) -> str:
        return f"({self.left} > {self.right})"


class LessThanExpression(CompareExpression):
    """
    小于表达式
    """
    
    def _operate(self, left: Any, right: Any) -> Any:
        return left < right
    
    def __str__(self) -> str:
        return f"({self.left} < {self.right})"


class LogicalExpression(BinaryExpression):
    """
    逻辑表达式基类
    """
    pass


class AndExpression(LogicalExpression):
    """
    逻辑与表达式
    """
    
    def _operate(self, left: Any, right: Any) -> Any:
        return bool(left) and bool(right)
    
    def __str__(self) -> str:
        return f"({self.left} AND {self.right})"


class OrExpression(LogicalExpression):
    """
    逻辑或表达式
    """
    
    def _operate(self, left: Any, right: Any) -> Any:
        return bool(left) or bool(right)
    
    def __str__(self) -> str:
        return f"({self.left} OR {self.right})"


class NotExpression(Expression):
    """
    逻辑非表达式
    """
    
    def __init__(self, expression: Expression):
        self.expression = expression
    
    def interpret(self, context: Dict[str, Any]) -> Any:
        return not bool(self.expression.interpret(context))
    
    def __str__(self) -> str:
        return f"(NOT {self.expression})"


# ============================================================================
# 2. 表达式解析器
# ============================================================================

class TokenType(Enum):
    """标记类型"""
    NUMBER = "NUMBER"
    STRING = "STRING"
    BOOLEAN = "BOOLEAN"
    IDENTIFIER = "IDENTIFIER"
    PLUS = "PLUS"
    MINUS = "MINUS"
    MULTIPLY = "MULTIPLY"
    DIVIDE = "DIVIDE"
    EQUALS = "EQUALS"
    GREATER = "GREATER"
    LESS = "LESS"
    AND = "AND"
    OR = "OR"
    NOT = "NOT"
    LPAREN = "LPAREN"
    RPAREN = "RPAREN"
    EOF = "EOF"


@dataclass
class Token:
    """标记"""
    type: TokenType
    value: str
    position: int


class Lexer:
    """
    词法分析器
    将输入字符串转换为标记序列
    """
    
    def __init__(self, text: str):
        self.text = text
        self.position = 0
        self.current_char = self.text[0] if text else None
    
    def error(self, message: str = "无效字符") -> None:
        """抛出词法分析错误"""
        raise ValueError(f"词法分析错误在位置 {self.position}: {message}")
    
    def advance(self) -> None:
        """移动到下一个字符"""
        self.position += 1
        if self.position >= len(self.text):
            self.current_char = None
        else:
            self.current_char = self.text[self.position]
    
    def skip_whitespace(self) -> None:
        """跳过空白字符"""
        while self.current_char is not None and self.current_char.isspace():
            self.advance()
    
    def read_number(self) -> str:
        """读取数字"""
        result = ''
        while (self.current_char is not None and 
               (self.current_char.isdigit() or self.current_char == '.')):
            result += self.current_char
            self.advance()
        return result
    
    def read_string(self) -> str:
        """读取字符串"""
        quote_char = self.current_char
        result = quote_char
        self.advance()
        
        while self.current_char is not None and self.current_char != quote_char:
            result += self.current_char
            self.advance()
        
        if self.current_char == quote_char:
            result += self.current_char
            self.advance()
        else:
            self.error("未闭合的字符串")
        
        return result
    
    def read_identifier(self) -> str:
        """读取标识符"""
        result = ''
        while (self.current_char is not None and 
               (self.current_char.isalnum() or self.current_char == '_')):
            result += self.current_char
            self.advance()
        return result
    
    def get_next_token(self) -> Token:
        """获取下一个标记"""
        while self.current_char is not None:
            if self.current_char.isspace():
                self.skip_whitespace()
                continue
            
            if self.current_char.isdigit():
                return Token(TokenType.NUMBER, self.read_number(), self.position)
            
            if self.current_char in ['"', "'"]:
                return Token(TokenType.STRING, self.read_string(), self.position)
            
            if self.current_char.isalpha() or self.current_char == '_':
                identifier = self.read_identifier()
                
                # 检查关键字
                if identifier.upper() == 'AND':
                    return Token(TokenType.AND, identifier, self.position)
                elif identifier.upper() == 'OR':
                    return Token(TokenType.OR, identifier, self.position)
                elif identifier.upper() == 'NOT':
                    return Token(TokenType.NOT, identifier, self.position)
                elif identifier.lower() in ['true', 'false']:
                    return Token(TokenType.BOOLEAN, identifier, self.position)
                else:
                    return Token(TokenType.IDENTIFIER, identifier, self.position)
            
            if self.current_char == '+':
                self.advance()
                return Token(TokenType.PLUS, '+', self.position - 1)
            
            if self.current_char == '-':
                self.advance()
                return Token(TokenType.MINUS, '-', self.position - 1)
            
            if self.current_char == '*':
                self.advance()
                return Token(TokenType.MULTIPLY, '*', self.position - 1)
            
            if self.current_char == '/':
                self.advance()
                return Token(TokenType.DIVIDE, '/', self.position - 1)
            
            if self.current_char == '=':
                self.advance()
                if self.current_char == '=':
                    self.advance()
                    return Token(TokenType.EQUALS, '==', self.position - 2)
                else:
                    self.error("期望 '=='")
            
            if self.current_char == '>':
                self.advance()
                return Token(TokenType.GREATER, '>', self.position - 1)
            
            if self.current_char == '<':
                self.advance()
                return Token(TokenType.LESS, '<', self.position - 1)
            
            if self.current_char == '(':
                self.advance()
                return Token(TokenType.LPAREN, '(', self.position - 1)
            
            if self.current_char == ')':
                self.advance()
                return Token(TokenType.RPAREN, ')', self.position - 1)
            
            self.error(f"无效字符: '{self.current_char}'")
        
        return Token(TokenType.EOF, '', self.position)


class Parser:
    """
    语法分析器
    将标记序列转换为抽象语法树
    """
    
    def __init__(self, lexer: Lexer):
        self.lexer = lexer
        self.current_token = self.lexer.get_next_token()
    
    def error(self, message: str = "语法错误") -> None:
        """抛出语法分析错误"""
        raise ValueError(f"语法分析错误: {message}")
    
    def eat(self, token_type: TokenType) -> None:
        """消费指定类型的标记"""
        if self.current_token.type == token_type:
            self.current_token = self.lexer.get_next_token()
        else:
            self.error(f"期望 {token_type.value}, 但得到 {self.current_token.type.value}")
    
    def factor(self) -> Expression:
        """解析因子"""
        token = self.current_token
        
        if token.type == TokenType.NUMBER:
            self.eat(TokenType.NUMBER)
            return TerminalExpression(token.value)
        
        elif token.type == TokenType.STRING:
            self.eat(TokenType.STRING)
            return TerminalExpression(token.value)
        
        elif token.type == TokenType.BOOLEAN:
            self.eat(TokenType.BOOLEAN)
            return TerminalExpression(token.value)
        
        elif token.type == TokenType.IDENTIFIER:
            self.eat(TokenType.IDENTIFIER)
            return TerminalExpression(token.value)
        
        elif token.type == TokenType.LPAREN:
            self.eat(TokenType.LPAREN)
            node = self.or_expr()
            self.eat(TokenType.RPAREN)
            return node
        
        elif token.type == TokenType.NOT:
            self.eat(TokenType.NOT)
            return NotExpression(self.factor())
        
        else:
            self.error(f"意外的标记: {token.value}")
    
    def term(self) -> Expression:
        """解析项"""
        node = self.factor()
        
        while self.current_token.type in (TokenType.MULTIPLY, TokenType.DIVIDE):
            token = self.current_token
            if token.type == TokenType.MULTIPLY:
                self.eat(TokenType.MULTIPLY)
                node = MultiplyExpression(node, self.factor())
            elif token.type == TokenType.DIVIDE:
                self.eat(TokenType.DIVIDE)
                node = DivideExpression(node, self.factor())
        
        return node
    
    def expr(self) -> Expression:
        """解析表达式"""
        node = self.term()
        
        while self.current_token.type in (TokenType.PLUS, TokenType.MINUS):
            token = self.current_token
            if token.type == TokenType.PLUS:
                self.eat(TokenType.PLUS)
                node = AddExpression(node, self.term())
            elif token.type == TokenType.MINUS:
                self.eat(TokenType.MINUS)
                node = SubtractExpression(node, self.term())
        
        return node
    
    def comparison(self) -> Expression:
        """解析比较表达式"""
        node = self.expr()
        
        while self.current_token.type in (TokenType.EQUALS, TokenType.GREATER, TokenType.LESS):
            token = self.current_token
            if token.type == TokenType.EQUALS:
                self.eat(TokenType.EQUALS)
                node = EqualsExpression(node, self.expr())
            elif token.type == TokenType.GREATER:
                self.eat(TokenType.GREATER)
                node = GreaterThanExpression(node, self.expr())
            elif token.type == TokenType.LESS:
                self.eat(TokenType.LESS)
                node = LessThanExpression(node, self.expr())
        
        return node
    
    def and_expr(self) -> Expression:
        """解析逻辑与表达式"""
        node = self.comparison()
        
        while self.current_token.type == TokenType.AND:
            self.eat(TokenType.AND)
            node = AndExpression(node, self.comparison())
        
        return node
    
    def or_expr(self) -> Expression:
        """解析逻辑或表达式"""
        node = self.and_expr()
        
        while self.current_token.type == TokenType.OR:
            self.eat(TokenType.OR)
            node = OrExpression(node, self.and_expr())
        
        return node
    
    def parse(self) -> Expression:
        """解析完整表达式"""
        node = self.or_expr()
        if self.current_token.type != TokenType.EOF:
            self.error("表达式解析不完整")
        return node


class ExpressionInterpreter:
    """
    表达式解释器
    提供高级接口来解释表达式
    """
    
    def __init__(self):
        self.context: Dict[str, Any] = {}
    
    def set_variable(self, name: str, value: Any) -> None:
        """设置变量值"""
        self.context[name] = value
    
    def get_variable(self, name: str) -> Any:
        """获取变量值"""
        return self.context.get(name)
    
    def clear_variables(self) -> None:
        """清除所有变量"""
        self.context.clear()
    
    def interpret(self, expression_text: str) -> Any:
        """解释表达式"""
        try:
            lexer = Lexer(expression_text)
            parser = Parser(lexer)
            ast = parser.parse()
            return ast.interpret(self.context)
        except Exception as e:
            raise ValueError(f"解释表达式失败: {e}")
    
    def parse_expression(self, expression_text: str) -> Expression:
        """解析表达式为AST"""
        lexer = Lexer(expression_text)
        parser = Parser(lexer)
        return parser.parse()


# ============================================================================
# 3. SQL查询解释器示例
# ============================================================================

class SQLTokenType(Enum):
    """SQL标记类型"""
    SELECT = "SELECT"
    FROM = "FROM"
    WHERE = "WHERE"
    AND = "AND"
    OR = "OR"
    EQUALS = "EQUALS"
    GREATER = "GREATER"
    LESS = "LESS"
    IDENTIFIER = "IDENTIFIER"
    STRING = "STRING"
    NUMBER = "NUMBER"
    COMMA = "COMMA"
    STAR = "STAR"
    SEMICOLON = "SEMICOLON"
    EOF = "EOF"


@dataclass
class SQLToken:
    """SQL标记"""
    type: SQLTokenType
    value: str


class SQLLexer:
    """
    SQL词法分析器
    """
    
    def __init__(self, text: str):
        self.text = text.upper()  # SQL不区分大小写
        self.position = 0
        self.current_char = self.text[0] if text else None
    
    def advance(self) -> None:
        """移动到下一个字符"""
        self.position += 1
        if self.position >= len(self.text):
            self.current_char = None
        else:
            self.current_char = self.text[self.position]
    
    def skip_whitespace(self) -> None:
        """跳过空白字符"""
        while self.current_char is not None and self.current_char.isspace():
            self.advance()
    
    def read_word(self) -> str:
        """读取单词"""
        result = ''
        while (self.current_char is not None and 
               (self.current_char.isalnum() or self.current_char == '_')):
            result += self.current_char
            self.advance()
        return result
    
    def read_string(self) -> str:
        """读取字符串"""
        quote_char = self.current_char
        result = ''
        self.advance()
        
        while self.current_char is not None and self.current_char != quote_char:
            result += self.current_char
            self.advance()
        
        if self.current_char == quote_char:
            self.advance()
        
        return result
    
    def read_number(self) -> str:
        """读取数字"""
        result = ''
        while (self.current_char is not None and 
               (self.current_char.isdigit() or self.current_char == '.')):
            result += self.current_char
            self.advance()
        return result
    
    def get_next_token(self) -> SQLToken:
        """获取下一个标记"""
        while self.current_char is not None:
            if self.current_char.isspace():
                self.skip_whitespace()
                continue
            
            if self.current_char.isalpha() or self.current_char == '_':
                word = self.read_word()
                
                # 检查关键字
                if word == 'SELECT':
                    return SQLToken(SQLTokenType.SELECT, word)
                elif word == 'FROM':
                    return SQLToken(SQLTokenType.FROM, word)
                elif word == 'WHERE':
                    return SQLToken(SQLTokenType.WHERE, word)
                elif word == 'AND':
                    return SQLToken(SQLTokenType.AND, word)
                elif word == 'OR':
                    return SQLToken(SQLTokenType.OR, word)
                else:
                    return SQLToken(SQLTokenType.IDENTIFIER, word)
            
            if self.current_char in ['"', "'"]:
                return SQLToken(SQLTokenType.STRING, self.read_string())
            
            if self.current_char.isdigit():
                return SQLToken(SQLTokenType.NUMBER, self.read_number())
            
            if self.current_char == '*':
                self.advance()
                return SQLToken(SQLTokenType.STAR, '*')
            
            if self.current_char == ',':
                self.advance()
                return SQLToken(SQLTokenType.COMMA, ',')
            
            if self.current_char == '=':
                self.advance()
                return SQLToken(SQLTokenType.EQUALS, '=')
            
            if self.current_char == '>':
                self.advance()
                return SQLToken(SQLTokenType.GREATER, '>')
            
            if self.current_char == '<':
                self.advance()
                return SQLToken(SQLTokenType.LESS, '<')
            
            if self.current_char == ';':
                self.advance()
                return SQLToken(SQLTokenType.SEMICOLON, ';')
            
            # 跳过未知字符
            self.advance()
        
        return SQLToken(SQLTokenType.EOF, '')


@dataclass
class SQLQuery:
    """SQL查询结构"""
    select_fields: List[str]
    from_table: str
    where_condition: Optional[Expression] = None
    
    def execute(self, data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """执行查询"""
        result = []
        
        for row in data:
            # 检查WHERE条件
            if self.where_condition:
                if not self.where_condition.interpret(row):
                    continue
            
            # 选择字段
            if '*' in self.select_fields:
                result.append(row.copy())
            else:
                selected_row = {}
                for field in self.select_fields:
                    if field in row:
                        selected_row[field] = row[field]
                result.append(selected_row)
        
        return result


class SQLParser:
    """
    SQL语法分析器
    """
    
    def __init__(self, lexer: SQLLexer):
        self.lexer = lexer
        self.current_token = self.lexer.get_next_token()
    
    def eat(self, token_type: SQLTokenType) -> None:
        """消费指定类型的标记"""
        if self.current_token.type == token_type:
            self.current_token = self.lexer.get_next_token()
        else:
            raise ValueError(f"期望 {token_type.value}, 但得到 {self.current_token.type.value}")
    
    def parse_select_fields(self) -> List[str]:
        """解析SELECT字段"""
        fields = []
        
        if self.current_token.type == SQLTokenType.STAR:
            self.eat(SQLTokenType.STAR)
            fields.append('*')
        else:
            fields.append(self.current_token.value)
            self.eat(SQLTokenType.IDENTIFIER)
            
            while self.current_token.type == SQLTokenType.COMMA:
                self.eat(SQLTokenType.COMMA)
                fields.append(self.current_token.value)
                self.eat(SQLTokenType.IDENTIFIER)
        
        return fields
    
    def parse_where_condition(self) -> Expression:
        """解析WHERE条件"""
        return self.parse_or_condition()
    
    def parse_or_condition(self) -> Expression:
        """解析OR条件"""
        node = self.parse_and_condition()
        
        while self.current_token.type == SQLTokenType.OR:
            self.eat(SQLTokenType.OR)
            node = OrExpression(node, self.parse_and_condition())
        
        return node
    
    def parse_and_condition(self) -> Expression:
        """解析AND条件"""
        node = self.parse_comparison()
        
        while self.current_token.type == SQLTokenType.AND:
            self.eat(SQLTokenType.AND)
            node = AndExpression(node, self.parse_comparison())
        
        return node
    
    def parse_comparison(self) -> Expression:
        """解析比较条件"""
        left = TerminalExpression(self.current_token.value)
        self.eat(SQLTokenType.IDENTIFIER)
        
        if self.current_token.type == SQLTokenType.EQUALS:
            self.eat(SQLTokenType.EQUALS)
            right = self.parse_value()
            return EqualsExpression(left, right)
        elif self.current_token.type == SQLTokenType.GREATER:
            self.eat(SQLTokenType.GREATER)
            right = self.parse_value()
            return GreaterThanExpression(left, right)
        elif self.current_token.type == SQLTokenType.LESS:
            self.eat(SQLTokenType.LESS)
            right = self.parse_value()
            return LessThanExpression(left, right)
        else:
            raise ValueError("期望比较操作符")
    
    def parse_value(self) -> Expression:
        """解析值"""
        if self.current_token.type == SQLTokenType.STRING:
            value = f"'{self.current_token.value}'"
            self.eat(SQLTokenType.STRING)
            return TerminalExpression(value)
        elif self.current_token.type == SQLTokenType.NUMBER:
            value = self.current_token.value
            self.eat(SQLTokenType.NUMBER)
            return TerminalExpression(value)
        elif self.current_token.type == SQLTokenType.IDENTIFIER:
            value = self.current_token.value
            self.eat(SQLTokenType.IDENTIFIER)
            return TerminalExpression(value)
        else:
            raise ValueError("期望值")
    
    def parse(self) -> SQLQuery:
        """解析SQL查询"""
        # SELECT
        self.eat(SQLTokenType.SELECT)
        select_fields = self.parse_select_fields()
        
        # FROM
        self.eat(SQLTokenType.FROM)
        from_table = self.current_token.value
        self.eat(SQLTokenType.IDENTIFIER)
        
        # WHERE (可选)
        where_condition = None
        if self.current_token.type == SQLTokenType.WHERE:
            self.eat(SQLTokenType.WHERE)
            where_condition = self.parse_where_condition()
        
        return SQLQuery(select_fields, from_table, where_condition)


class SQLInterpreter:
    """
    SQL解释器
    """
    
    def __init__(self):
        self.tables: Dict[str, List[Dict[str, Any]]] = {}
    
    def create_table(self, name: str, data: List[Dict[str, Any]]) -> None:
        """创建表"""
        self.tables[name] = data
    
    def execute_query(self, sql: str) -> List[Dict[str, Any]]:
        """执行SQL查询"""
        try:
            lexer = SQLLexer(sql)
            parser = SQLParser(lexer)
            query = parser.parse()
            
            if query.from_table not in self.tables:
                raise ValueError(f"表 '{query.from_table}' 不存在")
            
            table_data = self.tables[query.from_table]
            return query.execute(table_data)
        
        except Exception as e:
            raise ValueError(f"SQL执行失败: {e}")


# ============================================================================
# 4. 配置文件解释器示例
# ============================================================================

class ConfigTokenType(Enum):
    """配置文件标记类型"""
    IDENTIFIER = "IDENTIFIER"
    STRING = "STRING"
    NUMBER = "NUMBER"
    BOOLEAN = "BOOLEAN"
    EQUALS = "EQUALS"
    LBRACE = "LBRACE"
    RBRACE = "RBRACE"
    LBRACKET = "LBRACKET"
    RBRACKET = "RBRACKET"
    COMMA = "COMMA"
    NEWLINE = "NEWLINE"
    EOF = "EOF"


class ConfigLexer:
    """
    配置文件词法分析器
    """
    
    def __init__(self, text: str):
        self.text = text
        self.position = 0
        self.current_char = self.text[0] if text else None
    
    def advance(self) -> None:
        """移动到下一个字符"""
        self.position += 1
        if self.position >= len(self.text):
            self.current_char = None
        else:
            self.current_char = self.text[self.position]
    
    def skip_whitespace(self) -> None:
        """跳过空白字符（除了换行符）"""
        while (self.current_char is not None and 
               self.current_char.isspace() and 
               self.current_char != '\n'):
            self.advance()
    
    def skip_comment(self) -> None:
        """跳过注释"""
        if self.current_char == '#':
            while self.current_char is not None and self.current_char != '\n':
                self.advance()
    
    def read_string(self) -> str:
        """读取字符串"""
        quote_char = self.current_char
        result = ''
        self.advance()
        
        while self.current_char is not None and self.current_char != quote_char:
            if self.current_char == '\\':
                self.advance()
                if self.current_char == 'n':
                    result += '\n'
                elif self.current_char == 't':
                    result += '\t'
                elif self.current_char == 'r':
                    result += '\r'
                elif self.current_char == '\\':
                    result += '\\'
                elif self.current_char == quote_char:
                    result += quote_char
                else:
                    result += self.current_char
                self.advance()
            else:
                result += self.current_char
                self.advance()
        
        if self.current_char == quote_char:
            self.advance()
        
        return result
    
    def read_number(self) -> str:
        """读取数字"""
        result = ''
        while (self.current_char is not None and 
               (self.current_char.isdigit() or self.current_char == '.' or self.current_char == '-')):
            result += self.current_char
            self.advance()
        return result
    
    def read_identifier(self) -> str:
        """读取标识符"""
        result = ''
        while (self.current_char is not None and 
               (self.current_char.isalnum() or self.current_char in ['_', '-', '.'])):
            result += self.current_char
            self.advance()
        return result
    
    def get_next_token(self) -> Token:
        """获取下一个标记"""
        while self.current_char is not None:
            if self.current_char == '#':
                self.skip_comment()
                continue
            
            if self.current_char.isspace() and self.current_char != '\n':
                self.skip_whitespace()
                continue
            
            if self.current_char == '\n':
                self.advance()
                return Token(ConfigTokenType.NEWLINE, '\n', self.position)
            
            if self.current_char in ['"', "'"]:
                return Token(ConfigTokenType.STRING, self.read_string(), self.position)
            
            if self.current_char.isdigit() or self.current_char == '-':
                return Token(ConfigTokenType.NUMBER, self.read_number(), self.position)
            
            if self.current_char.isalpha() or self.current_char == '_':
                identifier = self.read_identifier()
                
                if identifier.lower() in ['true', 'false']:
                    return Token(ConfigTokenType.BOOLEAN, identifier, self.position)
                else:
                    return Token(ConfigTokenType.IDENTIFIER, identifier, self.position)
            
            if self.current_char == '=':
                self.advance()
                return Token(ConfigTokenType.EQUALS, '=', self.position)
            
            if self.current_char == '{':
                self.advance()
                return Token(ConfigTokenType.LBRACE, '{', self.position)
            
            if self.current_char == '}':
                self.advance()
                return Token(ConfigTokenType.RBRACE, '}', self.position)
            
            if self.current_char == '[':
                self.advance()
                return Token(ConfigTokenType.LBRACKET, '[', self.position)
            
            if self.current_char == ']':
                self.advance()
                return Token(ConfigTokenType.RBRACKET, ']', self.position)
            
            if self.current_char == ',':
                self.advance()
                return Token(ConfigTokenType.COMMA, ',', self.position)
            
            # 跳过未知字符
            self.advance()
        
        return Token(ConfigTokenType.EOF, '', self.position)


class ConfigParser:
    """
    配置文件语法分析器
    """
    
    def __init__(self, lexer: ConfigLexer):
        self.lexer = lexer
        self.current_token = self.lexer.get_next_token()
    
    def eat(self, token_type: ConfigTokenType) -> None:
        """消费指定类型的标记"""
        if self.current_token.type == token_type:
            self.current_token = self.lexer.get_next_token()
        else:
            raise ValueError(f"期望 {token_type.value}, 但得到 {self.current_token.type.value}")
    
    def skip_newlines(self) -> None:
        """跳过换行符"""
        while self.current_token.type == ConfigTokenType.NEWLINE:
            self.eat(ConfigTokenType.NEWLINE)
    
    def parse_value(self) -> Any:
        """解析值"""
        if self.current_token.type == ConfigTokenType.STRING:
            value = self.current_token.value
            self.eat(ConfigTokenType.STRING)
            return value
        
        elif self.current_token.type == ConfigTokenType.NUMBER:
            value = self.current_token.value
            self.eat(ConfigTokenType.NUMBER)
            try:
                if '.' in value:
                    return float(value)
                else:
                    return int(value)
            except ValueError:
                return value
        
        elif self.current_token.type == ConfigTokenType.BOOLEAN:
            value = self.current_token.value
            self.eat(ConfigTokenType.BOOLEAN)
            return value.lower() == 'true'
        
        elif self.current_token.type == ConfigTokenType.LBRACE:
            return self.parse_object()
        
        elif self.current_token.type == ConfigTokenType.LBRACKET:
            return self.parse_array()
        
        else:
            raise ValueError(f"意外的值类型: {self.current_token.type.value}")
    
    def parse_array(self) -> List[Any]:
        """解析数组"""
        self.eat(ConfigTokenType.LBRACKET)
        self.skip_newlines()
        
        array = []
        
        if self.current_token.type != ConfigTokenType.RBRACKET:
            array.append(self.parse_value())
            
            while self.current_token.type == ConfigTokenType.COMMA:
                self.eat(ConfigTokenType.COMMA)
                self.skip_newlines()
                if self.current_token.type != ConfigTokenType.RBRACKET:
                    array.append(self.parse_value())
        
        self.skip_newlines()
        self.eat(ConfigTokenType.RBRACKET)
        return array
    
    def parse_object(self) -> Dict[str, Any]:
        """解析对象"""
        self.eat(ConfigTokenType.LBRACE)
        self.skip_newlines()
        
        obj = {}
        
        while self.current_token.type == ConfigTokenType.IDENTIFIER:
            key = self.current_token.value
            self.eat(ConfigTokenType.IDENTIFIER)
            self.eat(ConfigTokenType.EQUALS)
            value = self.parse_value()
            obj[key] = value
            
            self.skip_newlines()
        
        self.eat(ConfigTokenType.RBRACE)
        return obj
    
    def parse_assignment(self) -> tuple[str, Any]:
        """解析赋值语句"""
        key = self.current_token.value
        self.eat(ConfigTokenType.IDENTIFIER)
        self.eat(ConfigTokenType.EQUALS)
        value = self.parse_value()
        return key, value
    
    def parse(self) -> Dict[str, Any]:
        """解析配置文件"""
        config = {}
        
        self.skip_newlines()
        
        while self.current_token.type != ConfigTokenType.EOF:
            if self.current_token.type == ConfigTokenType.IDENTIFIER:
                key, value = self.parse_assignment()
                config[key] = value
            
            self.skip_newlines()
        
        return config


class ConfigInterpreter:
    """
    配置文件解释器
    """
    
    def __init__(self):
        self.config: Dict[str, Any] = {}
    
    def load_from_string(self, config_text: str) -> Dict[str, Any]:
        """从字符串加载配置"""
        try:
            lexer = ConfigLexer(config_text)
            parser = ConfigParser(lexer)
            self.config = parser.parse()
            return self.config
        except Exception as e:
            raise ValueError(f"配置解析失败: {e}")
    
    def load_from_file(self, filename: str) -> Dict[str, Any]:
        """从文件加载配置"""
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                return self.load_from_string(f.read())
        except FileNotFoundError:
            raise ValueError(f"配置文件不存在: {filename}")
        except Exception as e:
            raise ValueError(f"读取配置文件失败: {e}")
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        keys = key.split('.')
        value = self.config
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        
        return value
    
    def set(self, key: str, value: Any) -> None:
        """设置配置值"""
        keys = key.split('.')
        config = self.config
        
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        
        config[keys[-1]] = value
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return self.config.copy()


# ============================================================================
# 5. 演示函数
# ============================================================================

def demonstrate_basic_interpreter():
    """
    演示基本解释器功能
    """
    print("\n=== 基本解释器演示 ===")
    
    interpreter = ExpressionInterpreter()
    
    # 设置变量
    interpreter.set_variable('x', 10)
    interpreter.set_variable('y', 5)
    interpreter.set_variable('name', 'Python')
    interpreter.set_variable('active', True)
    
    # 测试各种表达式
    expressions = [
        "x + y",
        "x * y - 3",
        "x > y",
        "x == 10",
        "active AND x > 0",
        "name == 'Python' OR x < 5",
        "NOT (x < y)",
        "(x + y) * 2",
        "x / y + 1.5"
    ]
    
    print("\n=== 表达式计算 ===")
    for expr in expressions:
        try:
            result = interpreter.interpret(expr)
            print(f"{expr} = {result}")
        except Exception as e:
            print(f"{expr} = 错误: {e}")
    
    # 测试复杂表达式
    print("\n=== 复杂表达式 ===")
    complex_expressions = [
        "x > 5 AND y < 10 AND active",
        "(x + y) > 10 OR name == 'Java'",
        "NOT active OR (x * y) > 40"
    ]
    
    for expr in complex_expressions:
        try:
            result = interpreter.interpret(expr)
            print(f"{expr} = {result}")
        except Exception as e:
            print(f"{expr} = 错误: {e}")


def demonstrate_sql_interpreter():
    """
    演示SQL解释器
    """
    print("\n=== SQL解释器演示 ===")
    
    # 创建SQL解释器
    sql_interpreter = SQLInterpreter()
    
    # 创建测试数据
    users_data = [
        {'id': 1, 'name': 'Alice', 'age': 25, 'city': 'Beijing'},
        {'id': 2, 'name': 'Bob', 'age': 30, 'city': 'Shanghai'},
        {'id': 3, 'name': 'Charlie', 'age': 35, 'city': 'Beijing'},
        {'id': 4, 'name': 'Diana', 'age': 28, 'city': 'Guangzhou'},
        {'id': 5, 'name': 'Eve', 'age': 22, 'city': 'Shanghai'}
    ]
    
    products_data = [
        {'id': 1, 'name': 'Laptop', 'price': 5000, 'category': 'Electronics'},
        {'id': 2, 'name': 'Phone', 'price': 3000, 'category': 'Electronics'},
        {'id': 3, 'name': 'Book', 'price': 50, 'category': 'Education'},
        {'id': 4, 'name': 'Desk', 'price': 800, 'category': 'Furniture'}
    ]
    
    # 创建表
    sql_interpreter.create_table('users', users_data)
    sql_interpreter.create_table('products', products_data)
    
    # 测试SQL查询
    queries = [
        "SELECT * FROM users",
        "SELECT name, age FROM users",
        "SELECT * FROM users WHERE age > 25",
        "SELECT * FROM users WHERE city = 'Beijing'",
        "SELECT * FROM users WHERE age > 25 AND city = 'Shanghai'",
        "SELECT * FROM products WHERE price < 1000",
        "SELECT name, price FROM products WHERE category = 'Electronics'"
    ]
    
    for query in queries:
        try:
            print(f"\n查询: {query}")
            result = sql_interpreter.execute_query(query)
            print(f"结果: {result}")
        except Exception as e:
            print(f"错误: {e}")


def demonstrate_config_interpreter():
    """
    演示配置文件解释器
    """
    print("\n=== 配置文件解释器演示 ===")
    
    # 示例配置文件内容
    config_text = """
# 数据库配置
database = {
    host = "localhost"
    port = 5432
    name = "myapp"
    username = "admin"
    password = "secret123"
    ssl_enabled = true
}

# 服务器配置
server = {
    host = "0.0.0.0"
    port = 8080
    debug = false
    workers = 4
}

# 日志配置
logging = {
    level = "INFO"
    file = "/var/log/app.log"
    max_size = 10485760
    backup_count = 5
}

# 功能开关
features = {
    user_registration = true
    email_notifications = true
    analytics = false
}

# 支持的语言
supported_languages = ["en", "zh", "ja", "ko"]

# API配置
api_keys = ["key1", "key2", "key3"]

# 缓存配置
cache_timeout = 3600
max_connections = 100
"""
    
    # 创建配置解释器
    config_interpreter = ConfigInterpreter()
    
    try:
        # 解析配置
        config = config_interpreter.load_from_string(config_text)
        
        print("\n=== 解析结果 ===")
        print(json.dumps(config, indent=2, ensure_ascii=False))
        
        # 测试配置访问
        print("\n=== 配置访问测试 ===")
        print(f"数据库主机: {config_interpreter.get('database.host')}")
        print(f"数据库端口: {config_interpreter.get('database.port')}")
        print(f"服务器调试模式: {config_interpreter.get('server.debug')}")
        print(f"日志级别: {config_interpreter.get('logging.level')}")
        print(f"支持的语言: {config_interpreter.get('supported_languages')}")
        print(f"缓存超时: {config_interpreter.get('cache_timeout')}")
        
        # 测试不存在的配置
        print(f"不存在的配置: {config_interpreter.get('nonexistent.key', 'default_value')}")
        
        # 动态设置配置
        config_interpreter.set('new_feature.enabled', True)
        config_interpreter.set('new_feature.version', '1.0')
        print(f"新功能启用: {config_interpreter.get('new_feature.enabled')}")
        print(f"新功能版本: {config_interpreter.get('new_feature.version')}")
        
    except Exception as e:
        print(f"配置解析失败: {e}")


def demonstrate_performance_comparison():
    """
    演示性能对比
    """
    print("\n=== 性能对比演示 ===")
    
    interpreter = ExpressionInterpreter()
    interpreter.set_variable('x', 100)
    interpreter.set_variable('y', 50)
    
    # 测试表达式解释器性能
    print("\n=== 表达式解释器性能测试 ===")
    
    expressions = [
        "x + y",
        "x * y - 100",
        "x > y AND x < 200",
        "(x + y) * 2 / 3"
    ]
    
    iterations = 1000
    
    for expr in expressions:
        start_time = time.time()
        
        for _ in range(iterations):
            interpreter.interpret(expr)
        
        end_time = time.time()
        avg_time = (end_time - start_time) / iterations * 1000
        print(f"{expr}: 平均 {avg_time:.3f}ms")
    
    # 与Python内置eval对比
    print("\n=== 与Python eval对比 ===")
    
    python_expressions = [
        "x + y",
        "x * y - 100",
        "x > y and x < 200",
        "(x + y) * 2 / 3"
    ]
    
    context = {'x': 100, 'y': 50}
    
    for i, expr in enumerate(python_expressions):
        # 自定义解释器
        start_time = time.time()
        for _ in range(iterations):
            interpreter.interpret(expressions[i])
        custom_time = time.time() - start_time
        
        # Python eval
        start_time = time.time()
        for _ in range(iterations):
            eval(expr, {"__builtins__": {}}, context)
        eval_time = time.time() - start_time
        
        print(f"{expr}:")
        print(f"  自定义解释器: {custom_time*1000:.3f}ms")
        print(f"  Python eval: {eval_time*1000:.3f}ms")
        print(f"  性能比: {custom_time/eval_time:.2f}x")


def demonstrate_java_comparison():
    """
    演示与Java的对比
    """
    print("\n=== Python vs Java 解释器模式对比 ===")
    
    print("\n=== Java实现特点 ===")
    print("""
    Java解释器模式的实现:
    
    // Java抽象表达式
    public abstract class Expression {
        public abstract Object interpret(Context context);
    }
    
    // Java终结符表达式
    public class TerminalExpression extends Expression {
        private String data;
        
        public TerminalExpression(String data) {
            this.data = data;
        }
        
        @Override
        public Object interpret(Context context) {
            return context.getValue(data);
        }
    }
    
    // Java非终结符表达式
    public class AddExpression extends Expression {
        private Expression left, right;
        
        public AddExpression(Expression left, Expression right) {
            this.left = left;
            this.right = right;
        }
        
        @Override
        public Object interpret(Context context) {
            return (Integer)left.interpret(context) + 
                   (Integer)right.interpret(context);
        }
    }
    """)
    
    print("\n=== Python实现优势 ===")
    print("""
    Python解释器模式的优势:
    
    1. 动态类型系统:
       - 不需要严格的类型声明
       - 支持多种数据类型的自动转换
    
    2. 内置解释能力:
       - eval()和exec()提供强大的解释功能
       - ast模块支持抽象语法树操作
    
    3. 正则表达式支持:
       - 强大的字符串处理能力
       - 简化词法分析实现
    
    4. 元编程特性:
       - 可以动态创建和修改解释器
       - 支持运行时代码生成
    
    5. 简洁的语法:
       - 减少样板代码
       - 提高开发效率
    """)
    
    print("\n=== 实际应用场景对比 ===")
    print("""
    应用场景对比:
    
    Java适合:
    - 大型编译器和解释器
    - 企业级DSL实现
    - 性能要求高的场景
    
    Python适合:
    - 配置文件解析
    - 简单的DSL实现
    - 脚本语言解释器
    - 数据查询语言
    - 规则引擎
    """)


def main():
    """
    主函数 - 演示所有解释器模式实现
    """
    print("解释器模式 (Interpreter Pattern) - Python实现演示")
    print("=" * 60)
    
    # 演示基本解释器
    demonstrate_basic_interpreter()
    
    # 演示SQL解释器
    demonstrate_sql_interpreter()
    
    # 演示配置文件解释器
    demonstrate_config_interpreter()
    
    # 演示性能对比
    demonstrate_performance_comparison()
    
    # 演示Java对比
    demonstrate_java_comparison()
    
    print("\n=== 总结 ===")
    print("""
    解释器模式的核心思想:
    1. 定义语言的文法表示
    2. 实现解释器来处理语言中的句子
    3. 将复杂的解释逻辑分解为简单的表达式
    
    Python实现的特点:
    1. 利用动态类型系统简化实现
    2. 使用内置的解释能力(eval, exec)
    3. 强大的字符串处理和正则表达式支持
    4. 元编程特性支持动态解释器创建
    
    适用场景:
    - 配置文件解析
    - 简单的DSL(领域特定语言)实现
    - 数据查询语言
    - 规则引擎
    - 脚本语言解释器
    """)


if __name__ == "__main__":
    main()